@model List<CaipuGuanliXitong.Models.WeeklyMenu>

@{
    ViewData["Title"] = "编辑每周菜谱";
    var cookBooks = ViewBag.CookBooks as List<CaipuGuanliXitong.Models.CookBook>;
    // 确保startDate是周一
    var startDate = ViewBag.StartDate;
    while (startDate.DayOfWeek != DayOfWeek.Monday)
    {
        startDate = startDate.AddDays(-1);
    }
}

<h2>编辑每周菜谱</h2>

<div class="row">
    <div class="col-md-12">
        <form method="get" action="@Url.Action("Index")" class="form-inline">
            <div class="form-group">
                <label for="startDate">周开始日期:</label>
                <input type="date" id="startDate" name="startDate" value="@startDate.ToString("yyyy-MM-dd")" class="form-control" />
            </div>
        </form>
    </div>
</div>

<form asp-action="Edit" method="post" id="weeklyMenuForm">
    @Html.AntiForgeryToken()
    <input type="hidden" name="startDate" value="@startDate" />
    <input type="hidden" name="menuDataJson" id="menuDataJson" />

    <table class="table table-bordered mt-3">
        <thead>
            <tr>
                <th>星期</th>
                <th colspan="2">早餐</th>
                <th colspan="2">午餐</th>
                <th colspan="2">晚餐</th>
            </tr>
            <tr>
                <th></th>
                <th>男</th>
                <th>女</th>
                <th>男</th>
                <th>女</th>
                <th>男</th>
                <th>女</th>
            </tr>
        </thead>
        <tbody>
            @{
                string[] weekdays = { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };
                int[] dayNumbers = { 1, 2, 3, 4, 5, 6, 7 };
                int[] mealNumbers = { 1, 2, 3 }; // 1=早餐, 2=午餐, 3=晚餐
                string[] mealNames = { "", "早餐", "午餐", "晚餐" };
                int[] genders = { 1, 2 }; // 1=男, 2=女
            }
            
            @for (int i = 0; i < weekdays.Length; i++)
            {
                <tr>
                    <td>
                        @weekdays[i]
                        <br />
                        <small>@startDate.AddDays(i).ToString("MM月dd日")</small>
                    </td>
                    @for (int j = 0; j < mealNumbers.Length; j++)
                    {
                        @for (int k = 0; k < genders.Length; k++)
                        {
                            <td>
                                @{
                                    var menu = Model?.FirstOrDefault(m => 
                                        m.DayOfWeek == dayNumbers[i] && 
                                        m.MealType == mealNumbers[j] && 
                                        m.Gender == genders[k]);
                                        
                                    var cellId = $"Day{dayNumbers[i]}_Meal{mealNumbers[j]}_Gender{genders[k]}";
                                    var selectedCookBooks = new List<(int Id, string Name)>();
                                    
                                    if (menu != null && !string.IsNullOrEmpty(menu.CookBookIds))
                                    {
                                        var ids = menu.CookBookIds.Split(',').Where(x => !string.IsNullOrEmpty(x)).Select(int.Parse).ToList();
                                        var names = menu.CookBookNames?.Split(',').Where(x => !string.IsNullOrEmpty(x)).ToList() ?? new List<string>();
                                        
                                        for (int l = 0; l < ids.Count && l < names.Count; l++)
                                        {
                                            selectedCookBooks.Add((ids[l], names[l]));
                                        }
                                    }
                                    else if (menu != null && menu.CookBookId.HasValue)
                                    {
                                        selectedCookBooks.Add((menu.CookBookId.Value, menu.CookBookName ?? ""));
                                    }
                                }
                                
                                <div id="selected-cookbooks-@cellId" class="selected-cookbooks mb-2">
                                    @foreach (var cookBook in selectedCookBooks)
                                    {
                                        <div class="badge badge-success mr-1" data-id="@cookBook.Id" style="background-color: #28a745; color: white; font-weight: bold;">
                                            @cookBook.Name
                                            <button type="button" class="btn-close btn-close-white ml-1 remove-cookbook" aria-label="Remove"></button>
                                        </div>
                                    }
                                </div>
                                
                                <button type="button" class="btn btn-sm btn-outline-primary select-cookbook-btn" 
                                        data-cell-id="@cellId" data-selected-ids="@string.Join(",", selectedCookBooks.Select(c => c.Id))">
                                    选择菜谱
                                </button>
                            </td>
                        }
                    }
                </tr>
            }
        </tbody>
    </table>

    <div class="form-group">
        <input type="submit" value="保存" class="btn btn-primary" />
        <a href="@Url.Action("Index", new { startDate = startDate })" class="btn btn-secondary">取消</a>
    </div>
</form>

<!-- 菜谱选择模态框 -->
<div class="modal fade" id="cookbookModal" tabindex="-1" role="dialog" aria-labelledby="cookbookModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="cookbookModalLabel">选择菜谱</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <input type="text" id="cookbookSearch" class="form-control" placeholder="搜索菜谱..." />
                </div>
                <div id="cookbook-list" class="cookbook-list" style="max-height: 400px; overflow-y: auto;">
                    @if (cookBooks != null)
                    {
                        @foreach (var cookBook in cookBooks)
                        {
                            <div class="form-check cookbook-item" data-id="@cookBook.Id" data-name="@cookBook.Name">
                                <input class="form-check-input" type="checkbox" id="cookbook_@cookBook.Id">
                                <label class="form-check-label" for="cookbook_@cookBook.Id">@cookBook.Name</label>
                            </div>
                        }
                    }
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="cancelButton" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmSelection">确认选择</button>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        let currentCellId = null;
        let selectedCookbookIds = [];
        let originalSelectedCookbookIds = []; // 保存原始选择，用于取消时恢复
        
        document.addEventListener('DOMContentLoaded', function() {
            // 选择菜谱按钮点击事件
            document.querySelectorAll('.select-cookbook-btn').forEach(button => {
                button.addEventListener('click', function() {
                    currentCellId = this.getAttribute('data-cell-id');
                    const selectedIds = this.getAttribute('data-selected-ids');
                    
                    // 清除之前的选择
                    document.querySelectorAll('.cookbook-item input[type="checkbox"]').forEach(checkbox => {
                        checkbox.checked = false;
                    });
                    
                    // 设置当前已选择的菜谱
                    selectedCookbookIds = selectedIds ? selectedIds.split(',').map(id => parseInt(id)).filter(id => !isNaN(id)) : [];
                    originalSelectedCookbookIds = [...selectedCookbookIds]; // 保存原始选择
                    
                    selectedCookbookIds.forEach(id => {
                        const checkbox = document.querySelector(`#cookbook_${id}`);
                        if (checkbox) {
                            checkbox.checked = true;
                        }
                    });
                    
                    // 清空搜索框
                    document.getElementById('cookbookSearch').value = '';
                    // 显示所有项目
                    document.querySelectorAll('.cookbook-item').forEach(item => {
                        item.style.display = '';
                    });
                    
                    // 显示模态框
                    $('#cookbookModal').modal('show');
                });
            });
            
            // 搜索功能
            document.getElementById('cookbookSearch').addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                document.querySelectorAll('.cookbook-item').forEach(item => {
                    const name = item.getAttribute('data-name').toLowerCase();
                    if (name.includes(searchTerm)) {
                        item.style.display = '';
                    } else {
                        item.style.display = 'none';
                    }
                });
            });
            
            // 确认选择按钮点击事件
            document.getElementById('confirmSelection').addEventListener('click', function() {
                // 获取选中的菜谱
                const selectedCookbooks = [];
                document.querySelectorAll('.cookbook-item input[type="checkbox"]:checked').forEach(checkbox => {
                    const item = checkbox.closest('.cookbook-item');
                    const id = parseInt(item.getAttribute('data-id'));
                    const name = item.getAttribute('data-name');
                    selectedCookbooks.push({ id, name });
                });
                
                // 更新隐藏的选中ID列表（用于提交）
                selectedCookbookIds = selectedCookbooks.map(c => c.id);
                const button = document.querySelector(`.select-cookbook-btn[data-cell-id="${currentCellId}"]`);
                if (button) {
                    button.setAttribute('data-selected-ids', selectedCookbookIds.join(','));
                }
                
                // 更新显示区域
                const displayArea = document.getElementById(`selected-cookbooks-${currentCellId}`);
                if (displayArea) {
                    displayArea.innerHTML = '';
                    selectedCookbooks.forEach(cookbook => {
                        const badge = document.createElement('div');
                        badge.className = 'badge badge-success mr-1';
                        badge.setAttribute('data-id', cookbook.id);
                        badge.style = 'background-color: #28a745; color: white; font-weight: bold;';
                        badge.innerHTML = `
                            ${cookbook.name}
                            <button type="button" class="btn-close btn-close-white ml-1 remove-cookbook" aria-label="Remove"></button>
                        `;
                        displayArea.appendChild(badge);
                    });
                }
                
                // 关闭模态框
                $('#cookbookModal').modal('hide');
            });
            
            // 取消按钮点击事件
            document.getElementById('cancelButton').addEventListener('click', function() {
                // 恢复原始选择
                selectedCookbookIds = [...originalSelectedCookbookIds];
                
                // 重置搜索框和列表显示
                document.getElementById('cookbookSearch').value = '';
                document.querySelectorAll('.cookbook-item').forEach(item => {
                    item.style.display = '';
                });
                
                // 关闭模态框
                $('#cookbookModal').modal('hide');
            });
            
            // 处理模态框关闭事件（包括按ESC键或点击背景遮罩）
            $('#cookbookModal').on('hidden.bs.modal', function (e) {
                // 恢复原始选择
                selectedCookbookIds = [...originalSelectedCookbookIds];
                
                // 重置搜索框和列表显示
                document.getElementById('cookbookSearch').value = '';
                document.querySelectorAll('.cookbook-item').forEach(item => {
                    item.style.display = '';
                });
            });
            
            // 移除菜谱按钮事件
            document.addEventListener('click', function(e) {
                if (e.target.classList.contains('remove-cookbook')) {
                    const badge = e.target.closest('.badge');
                    if (badge) {
                        const id = parseInt(badge.getAttribute('data-id'));
                        const cellContainer = e.target.closest('td');
                        if (cellContainer) {
                            const button = cellContainer.querySelector('.select-cookbook-btn');
                            if (button) {
                                const cellId = button.getAttribute('data-cell-id');
                                // 从显示中移除
                                badge.remove();
                                
                                // 更新按钮上的数据
                                const selectedIds = button.getAttribute('data-selected-ids').split(',').map(x => parseInt(x)).filter(x => !isNaN(x) && x !== id);
                                button.setAttribute('data-selected-ids', selectedIds.join(','));
                            }
                        }
                    }
                }
            });
            
            // 表单提交事件
            const form = document.getElementById('weeklyMenuForm');
            if (form) {
                form.addEventListener('submit', function(e) {
                    // 收集所有选择的数据
                    var menuData = {};
                    document.querySelectorAll('.select-cookbook-btn').forEach(button => {
                        const cellId = button.getAttribute('data-cell-id');
                        const selectedIds = button.getAttribute('data-selected-ids');
                        menuData[cellId] = selectedIds ? selectedIds.split(',').map(id => parseInt(id)).filter(id => !isNaN(id)) : [];
                    });
                    
                    // 将数据转换为JSON并放入隐藏字段
                    const jsonData = JSON.stringify(menuData);
                    document.getElementById('menuDataJson').value = jsonData;
                });
            }
        });
    </script>
    <script>
        // 点击周开始日期输入框时自动弹出日期控件
        document.addEventListener('DOMContentLoaded', function() {
            const startDateInput = document.getElementById('startDate');
            if (startDateInput) {
                startDateInput.addEventListener('click', function() {
                    this.showPicker();
                });
            }
        });
    </script>
}